import React, { Component } from "react";
import "../assets/css/OrderCard.css";
import ShopBagItem from "../components/ShopBagItem";
import login from "../hooks/loginInfo";
import {successToast} from "../components/Toast"

class OrderCard extends Component {
  constructor(props) {
    super(props);

    this.state = {
      order: this.props.order,
      createTime: null,
      totalNum: null,
      totalPrice: null,
      token:null
    };
    this.affirm = this.affirm.bind(this)
    this.del = this.del.bind(this)
  }

  del(){
    this.$axios.post("/removeOrder",{
        tokenString:this.state.token,
        oid:this.state.order.oid
    }).then(res=>{
        successToast(res.data.msg)
    })
    this.props.successGoods(this.state.order.oid)
  }

  affirm(){
    this.$axios.post("/receive",{
        tokenString:this.state.token,
        oid:this.state.order.oid
    }).then(res=>{
        successToast(res.data.msg)
    })
    this.props.affirmGoods(this.state.order.oid)
  }

  componentWillMount() {
    var loginInfo = login()
    var time = this.props.order.createTime.split("T");
    var t2 = time[1].split(".")[0];

    var totalNum = 0;
    var totalPrice = 0;
    this.props.order.children.forEach((item) => {
      totalNum += item.count;
      totalPrice += item.count * item.price;
    });
    this.setState({
      createTime: time[0] + " " + t2,
      totalNum,
      totalPrice,
      token:loginInfo.token
    });
  }

  render() {
    return (
      <div className="OrderCard">
        <div className="OrderCard_header">
          <span className="order_oid">{this.state.order.oid}</span>
          {this.state.order.status === 1 ? (
            <span className="order_affirm" onClick={this.affirm}>确认收货</span>
          ) : (
            <div className="order_success">
                <span>已完成</span>
                <i onClick={this.del}></i>
            </div>
          )}
        </div>
        <div className="order_productList">
          {this.state.order.children.map((item) => {
            return <ShopBagItem key={item.id} item={item}></ShopBagItem>;
          })}
        </div>
        <div className="order_total">
          <span className="ball_left"></span>
          <span className="ball_right"></span>
          <div className="order_total_createTime">{this.state.createTime}</div>
          <div className="order_total_num">
            <span>共计 {this.state.totalNum} 件商品</span>
            <span>合计 ￥{this.state.totalPrice}</span>
          </div>
        </div>
      </div>
    );
  }
}

export default OrderCard;
